package modelo.hibernate.dao;

import java.util.ArrayList;
import java.util.List;

import modelo.entidad.*;
import modelo.hibernate.config.Sesion;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class DaoMarcas {
	
	private Sesion sesionPostgres;
	
	public void agregarMarca(Marca dato) throws Exception{
		
		@SuppressWarnings("static-access")
		Session em = sesionPostgres.openSession();  
         Transaction tx = null;  
         try {    
        	 tx = em.beginTransaction();
              em.save(dato);   
              tx.commit();  
         } catch (Exception e) {  
             tx.rollback();            
             e.printStackTrace();
             throw e;
         } finally {  
             em.close();  
         }				
	}
	
	public List<Marca> obtenerTodas() throws Exception {
		List<Marca> datos = new ArrayList<Marca>();  
		  Session em = sesionPostgres.openSession();  	
	        try {  	
		    datos =  (List<Marca>) em.createCriteria(Marca.class).list();             
	        } catch (Exception e) {             
	       
	         throw new Exception(e.getMessage(),e.getCause());
	        } finally {  
	          em.close();  
	        } 
	        return datos;
	}
	
	public void actualizarMarca(Marca dato) throws Exception {
		@SuppressWarnings("static-access")
		Session em = sesionPostgres.openSession();  
         Transaction tx = null;  
         try {    
        	 tx = em.beginTransaction();
              em.update(dato);   
              tx.commit();  
         } catch (Exception e) {  
             tx.rollback();            
             e.printStackTrace();
             throw e;
         } finally {  
             em.close();  
         }		
	}

	public Marca encontrarMarcaporNombre(String nombre) throws Exception{
		Marca dato = new Marca();
		Session em = sesionPostgres.openSession();
		try{
			dato = (Marca)em.createQuery("SELECT p FROM Marca p WHERE descripcion= '"+nombre+"'").uniqueResult();
			
		}catch(Exception e){
			throw new Exception(e.getMessage(),e.getCause());
		}finally {  
	          em.close();  
	    }
		return dato;
	}
	
}
